package com.cskaoyan.service.wx;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;

import com.cskaoyan.bean.vo.wx.aftersale.AfterSaleVo;
import com.cskaoyan.mapper.MarketAftersaleMapper;
import com.cskaoyan.mapper.MarketOrderGoodsMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author by yxy_8175@163.com
 * @Description TODO
 * @Date 2022-11-24 11:07
 */

@Service
public class AfterSaleServiceImpl implements AfterSaleService{

    @Autowired
    private MarketAftersaleMapper aftersaleMapper;
    @Autowired
    private MarketOrderGoodsMapper orderGoodsMapper;


    @Override
    public CommonData<AfterSaleVo> queryAllAfterSale(BasePageInfo pageInfo, Short status,Integer userId) {
        PageHelper.startPage(pageInfo.getPage(),pageInfo.getLimit());

        // 存放结果的容器
        List<AfterSaleVo> resultAfterSale = new ArrayList<>();

        MarketAftersaleExample example = new MarketAftersaleExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false).andStatusEqualTo(status);
        List<MarketAftersale> marketAftersales = aftersaleMapper.selectByExample(example);

        for (MarketAftersale marketAftersale : marketAftersales) {
            AfterSaleVo afterSaleVo = new AfterSaleVo();
            // 将售后信息放入
            afterSaleVo.setAftersale(marketAftersale);
            Integer orderId = marketAftersale.getOrderId();

            MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
            orderGoodsExample.or().andDeletedEqualTo(false).andOrderIdEqualTo(orderId);

            List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            // 将查处出的订单商品信息放入
            afterSaleVo.setGoodsList(marketOrderGoods);

            resultAfterSale.add(afterSaleVo);
        }
        // 分页处理
        PageInfo<AfterSaleVo> page = new PageInfo<>(resultAfterSale);

        return CommonData.data(page);
    }

    @Override
    public void insertAfterSale(MarketAftersale aftersale) {
        // 生成 售后处理订单号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String afterSaleSn = sdf.format(new Date());

        aftersale.setAftersaleSn(afterSaleSn);
        aftersale.setAddTime(new Date());
        aftersale.setUpdateTime(new Date());

        aftersaleMapper.insertSelective(aftersale);
    }
}
